package org.elsa.fingobtb.common.func

import org.elsa.fingobtb.common.config.Account
import org.elsa.fingobtb.common.utils.Https
import org.elsa.fingobtb.common.utils.MD5s
import org.elsa.fingobtb.entity.request.*
import org.springframework.stereotype.Component
import kotlin.reflect.full.memberProperties



/**
 * btb restful api
 *
 * @author valord577
 * @date 2018/7/16 18:07
 */
@Component
class BtbRestfulBase {

    /**
     * 行情
     */
    fun ticker(symbol: String): String? {
        return ofGet("https://www.btb.com/api/v2/spot/products/$symbol/ticker")
    }

    /**
     * 深度
     */
    fun book(symbol: String, size: Int?): String? {
        var si = "200"
        if (null != size && size < 200) {
            si = "$size"
        }

        return ofGet("https://www.btb.com/api/v2/spot/products/$symbol/book?size=$si")
    }

    /**
     * k线
     */
    fun candles(symbol: String, type: String, size: Int?, start: Int?): String? {
        var si = ""
        var st = ""

        if (null != size) {
            si = "$size"
        }

        if (null != start) {
            st = "$start"
        }

        return ofGet("https://www.btb.com/api/v2/spot/products/$symbol/candles?type=$type&size=$si&start=$st")
    }

    /**
     * 下单
     */
    fun doTrade(entity: DoTrade): String? {
        return ofPost(entity, "https://www.btb.com/api/v2/spot/trade.do")
    }

    /**
     * 撤单
     */
    fun cancelOrder(entity: CancelOrder): String? {
        return ofPost(entity, "https://www.btb.com/api/v2/spot/cancel_order.do")
    }

    /**
     * 查资金
     */
    fun checkFunds(): String? {
        return ofPost(null, "https://www.btb.com/api/v2/spot/userinfo.do")
    }

    /**
     * 查委托 (查历史订单)
     */
    fun hisOrder(entity: HistoricalOrder): String? {
        return ofPost(entity, "https://www.btb.com/api/v2/spot/order_history.do")
    }

    /**
     * 获取用户的订单信息
     */
    fun orderInfo(entity: OrderInfo): String? {
        return ofPost(entity, "https://www.btb.com/api/v2/spot/order_info.do")
    }

    /**
     * 获取某个交易币对的交易信息
     */
    fun coinTrades(symbol: String): String? {
        return ofGet("https://www.btb.com/api/v2/spot/products/$symbol/trades")
    }

    /**
     * 获取交易币对信息
     */
    fun coinTotal(): String? {
        return ofGet("https://www.btb.com/api/v2/spot/products/")
    }

    /*--------------------------------------------------------------------*/

    /**
     * 获取市场
     */
    fun getMarkets(): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/markets.json")
    }

    /**
     * 获取所有市场的股票代码
     */
    fun getTickers(): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/tickers.json")
    }

    /**
     * 获取特定市场的股票代码
     */
    fun getSpecTickers(symbol: String): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/tickers/$symbol.json")
    }

    /**
     * 获取您的个人资料和帐户信息
     */
    fun getMembers(access_key: String, tonce: Long, signature: String): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/members/me.json?access_key=$access_key&tonce=$tonce&signature=$signature")
    }

    /**
     * 获取您的存款记录
     */
    fun getDeposits(access_key: String, tonce: Long, signature: String, currency: String, limit: Integer, state: String): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/deposits.json?access_key=$access_key&tonce=$tonce&signature=$signature&currency=$currency&limit=$limit&state=$state")
    }

    /**
     * 获取具体存款的详细信息
     */
    fun getDeposit(access_key: String, tonce: Long, signature: String, txid: String): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/deposit.json?access_key=$access_key&tonce=$tonce&signature=$signature&txid=$txid")
    }

    /**
     * 在哪里存款。 当生成新地址时，地址字段可能为空（例如，对于比特币），在这种情况下您应该稍后再试
     */
    fun getDepositAddress(access_key: String, tonce: Long, signature: String, currency: String): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/deposit_address.json?access_key=$access_key&tonce=$tonce&signature=$signature&currency=$currency")
    }

    /**
     * 分页获取订单
     */
    fun getOrders(access_key: String, tonce: Long, signature: String, market: String, state: String, limit: Integer, page: Integer, order_by: String): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/orders.json?access_key=$access_key&tonce=$tonce&signature=$signature&market=$market&state=$state&limit=$limit&page=$page&order_by=$order_by")
    }

    /**
     * 创建订单
     */
    fun createOrder(co: CreateOrder): String? {
        return cofPost(co, "https://api.coinfit.io:443/api/v2/orders.json")
    }

    /**
     * 创建多个订单
     */
    fun createOrders(cos: CreateOrders): String? {
        return ofPost(cos, "https://api.coinfit.io:443/api/v2/orders.json")
    }

    /**
     * 取消我的所有订单
     */
    fun cancelAllMyOrders(camo: CancelAllMyOrders): String? {
        return ofPost(camo, "https://api.coinfit.io:443/api/v2/orders/clear.json")
    }

    /**
     * 获取订单
     */
    fun getOrder(access_key: String, tonce: Long, signature: String, id: Integer): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/order.json?access_key=$access_key&tonce=$tonce&signature=$signature&id=$id")
    }

    /**
     * 获取指定市场的订单
     */
    fun getOrderBook(market: String,asks_limit: Integer, bids_limit: Integer): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/order_book.json?market=$market&asks_limit=$asks_limit&bids_limit=$bids_limit")
    }

    /**
     * 删除订单
     */
    fun deleteOrder(deo: DeleteOrder): String? {
        return ofPost(deo,"https://api.coinfit.io:443/api/v2/order/delete.json")
    }

    /**
     * 获得深度或指定市场。 要求和出价都从最高价格到最低价格排序
     */
    fun getDepth(market: String): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/depth.json?market=$market&limit=300")
    }

    /**
     * 获取市场上的近期交易，每笔交易仅包含一次。 交易按反向创建顺序排序
     */
    fun getTrades(market: String, limit: Integer, timestamp: Integer, from: Integer, to: Integer): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/trades.json?market=$market&limit=$limit&timestamp=$timestamp&from=$from&to=$to")
    }

    /**
     *获得执行的交易
     */
    fun getMyTrades(access_key: String, tonce: Long, signature: String, market: String, limit: Integer, from: Integer, to: Integer, order_by: String, timestamp: Integer): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/trades/my.json?access_key=$access_key&tonce=$tonce&signature=$signature&market=$market&limit=$limit&timestamp=$timestamp&from=$from&to=$to&order=$order_by")
    }

    /**
     * K线
     */
    fun getKLine(market: String, limit: Integer, period: Integer, timestamp: Integer): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/k.json?market=$market&limit=$limit&period=$period&timestamp=$timestamp")
    }

    /**
     * 获取具有待处理交易的K数据，这些交易尚未包含在K数据中，因为K数据生成器生成和处理的交易之间存在延迟
     */
    fun getKWithPendingTrades(market: String, trade_id: Integer, limit: Integer, period: Integer, timestamp: Integer): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/k_with_pending_trades.json?market=$market&trade_id=$trade_id&limit=$limit&period=$period&timestamp=$timestamp")
    }

    /**
     * 获取当前时间戳
     */
    fun getTimeStamp(): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/timestamp.json")
    }

    /**
     * 获取加密货币提款
     */
    fun cryptocurrencyWithdraws(access_key: String, tonce: Long, signature: String, currency: String, limit: Integer, state: String): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/withdraws.json?access_key=$access_key&tonce=$tonce&signature=$signature&currency=$currency&limit=$limit&state=$state")
    }

    /**
     * 根据id获取加密货币提款
     */
    fun getYourCryptocurrencyWithdraws(access_key: String, tonce: Long, signature: String, id: String): String? {
        return ofGet("https://api.coinfit.io:443/api/v2/withdraw.json?access_key=$access_key&tonce=$tonce&signature=$signature&id=$id")
    }

    /**
     * Create a withdraw
     */
    fun CreateWithraw(cw: CreateWithraw): String? {
        return ofPost(cw, "https://api.coinfit.io:443/api/v2/withdraw.json")
    }


    /**
     * 获取RMB与其他币种的换算
     */
    fun rmb2Coin(): String? {
        return ofGet("https://www.btb.com/api/ticker/v1/average/home/list?recommendLevel=0")
    }

    /**
     * 基础操作 post
     */
    private fun ofPost(entity: Any?, url: String): String? {
        val param = HashMap<String, String>(16)
        param["api_key"] = Account.apiKey
        if (null != entity) {
            entity.javaClass.kotlin.memberProperties.forEach {
                if (null != it.get(entity)) {
                    param[it.name] = it.get(entity).toString()
                }
            }
        }

        param["sign"] = MD5s.buildMysignV1(param, Account.secretKey)

        return Https.post(url, param)
    }

    private fun cofPost(entity: Any?, url: String): String? {
        val param = HashMap<String, String>(16)
        if (null != entity) {
            entity.javaClass.kotlin.memberProperties.forEach {
                if (null != it.get(entity)) {
                    param[it.name] = it.get(entity).toString()
                }
            }
        }
        return Https.post(url, param)
    }

    /**
     * 基础操作 get
     */
    private fun ofGet(url: String): String? {
        return Https.get(url)
    }
}